<?php
/**
 * 服务模块
 *
 * User: Jay
 * Date: 2018/8/8
 */

namespace AdminBundle\Controller;


use AdminBundle\RBAC\Item;
use AdminBundle\Entity\Menu;
use AdminBundle\Model\m_menu;
use AdminBundle\Model\m_permission;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class AuthPermissionController extends AdminController
{
    public function settingAction()
    {
        $r = $this->inlet($this->getParameter('return_page'), false);
        if ($r !== true) {
            return $r;
        }

        // 更新menu
        $m_menu = new m_menu($this->container);
        $m_menu->builtInData();

        $rbac = $this->get('rbac');
        $routeCollection = $this->get('router')->getRouteCollection();

        $routes = $routeCollection->all();
        $em = $this->getDoctrine()->getManager();
        $menuRepository = $this->getDoctrine()->getRepository(Menu::class);
        foreach ($routes as $k => $route) {
            if ($route->hasOption('permission_name')) {
                $permissionName = $route->getOption('permission_name');

                if (!$permission = $rbac->getPermission($permissionName)) {
                    $permission = $rbac->createPermission($permissionName);
                }
                $permission->description = $route->getOption('permission_desc') ?: '';
                $permission->menuId = 0;
                if ($route->hasOption('menu_tag')) {
                    $menu = $menuRepository->findOneBy(array('tag' => $route->getOption('menu_tag')));
                    if ($menu) {
                        $permission->menuId = $menu->getId();
                        $menu->setIsBindPermission(true);
                        $em->persist($menu);
                        $em->flush();
                    }
                }

                try {
                    if ($permission->createdAt) {
                        $rbac->update($permissionName, $permission);
                    } else {
                        $rbac->add($permission);
                    }
                } catch (\Exception $e) {
//                    dump($e->getMessage());
//                    dump($permission);
//                    exit();
                }
            }
        }

        // 追加内置的其他权限
        $m_permission = new m_permission($this->container);
        $m_permission->builtInData();

        return new Response('执行成功');
    }

    /**
     * 权限搜索
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function searchAction(Request $request)
    {
        $name = $request->query->get('id');
        $target = $request->query->get('target');

        $where = '';
        if ($request->query->get('term')) {
            $where .= ' AND i.description LIKE "%' . $request->query->get('term') . '%"';
        }

        $data = array();
        if ($target == 'avaliable') {
            // 检索可用的权限
            $data = $this->get('database_connection')
                ->fetchAll('SELECT name, description, type FROM auth_item i '
                    . 'WHERE NOT EXISTS(SELECT * FROM auth_item_child WHERE parent = ? AND i.name = child) '
                    . 'AND name != ?' . $where . ' ORDER BY type ASC',
                    array($name, $name)
                );
        } elseif ($target) {
            // 检索已分配的权限
            $data = $this->get('database_connection')
                ->fetchAll('SELECT name, description, type FROM auth_item_child ic '
                    . 'LEFT JOIN auth_item i ON i.name = ic.child '
                    . 'WHERE ic.parent = ? ' . $where . ' ORDER BY type ASC',
                    array($name)
                );
        }

        $result = array();
        foreach ($data as $v) {
            if ($v['type'] == Item::TYPE_ROLE) {
                $result['Roles'][$v['name']] = $v['description'];
            } else {
                $result['Permissions'][$v['name']] = $v['description'];
            }
        }

        return new JsonResponse($result);
    }
}